package com.fyt.ZhongYaoApp.Controller;

import com.fyt.ZhongYaoApp.pojo.Result;
import com.fyt.ZhongYaoApp.pojo.User;
import com.fyt.ZhongYaoApp.service.UserService;
import com.fyt.ZhongYaoApp.utils.JwtUtil;
import com.fyt.ZhongYaoApp.utils.Md5Util;
import com.fyt.ZhongYaoApp.utils.ThreadLocalUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@RestController
@RequestMapping("/user")
@Tag(name = "用户接口", description = "流程定义 API")
@ApiResponses(@ApiResponse(responseCode = "200", description = "接口请求成功"))
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

//    @Autowired
//    private PasswordEncoder passwordEncoder;

    @RequestMapping("/findById")
    public User selectById(int id)
    {
        return userService.findByID(id);
    }


    @Operation(summary = "注册", security = @SecurityRequirement(name = "ZhongYaoApp"))
    @PostMapping("/register")
    public Result register(@RequestBody User user) {

        // 查询用户
        User u = userService.findByUserName(user.getUsername());
        if (u == null) {
            // 没有占用 // 注册
            userService.register(user.getUsername(),user.getPassword());
            return Result.success();
        }else{
            // 占用了
            return Result.error("用户名已存在");
        }

    }

    @Operation(summary = "登录", security = @SecurityRequirement(name = "ZhongYaoApp"))
    @PostMapping("/login")
    public Result<Map> login(@RequestBody User user) {

        // 根据用户名查询用户
        User loginUser = userService.findByUserName(user.getUsername());

        System.out.println(loginUser);

        // 判断用户是否存在
        if(loginUser == null){
            return Result.error("用户名错误");
        }
        // 判断密码是否正确
        if (Md5Util.checkPassword(user.getPassword(), loginUser.getPassword())){
            // 登录成功
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",loginUser.getId());
            claims.put("username",loginUser.getUsername());
            claims.put("password",user.getPassword());
            claims.put("userPic",loginUser.getUserPic());
            claims.put("nickname",loginUser.getNickname());
            String token = JwtUtil.genToken(claims);
            claims.put("token",token);

            System.out.println(token);
//            // 把token存到redis中
//            ValueOperations<String,String> ops = stringRedisTemplate.opsForValue();
//            ops.set(token,token,1, TimeUnit.HOURS);
            return Result.success(claims);
        }

        return Result.error("密码错误");
    }

    @Operation(summary = "查询用户信息",security = @SecurityRequirement(name = "authScheme"))
    @PostMapping("/userInfo")
    public Result<User> userInfo(@RequestHeader(name = "Authorization")String token){
        // 根据用户名查询用户
//        Map<String,Object> map = JwtUtil.parseToken(token);
//        String username = (String) map.get("username");
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);
    }

    @Operation(summary = "更新用户信息",security = @SecurityRequirement(name = "authScheme"))
    @PostMapping("/update")
    public Result update(@RequestBody @Validated User user){
        userService.update(user);
        return Result.success("更新成功");
    }

    @Operation(summary = "修改用户密码",security = @SecurityRequirement(name = "authScheme"))
    @PostMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        //1 校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }
        // 原密码是否正确
        // 调用userService根据用户名拿到密码
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String)map.get("username");
        User loginUser = userService.findByUserName(username);
        if(!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))){
            return Result.error("原密码不正确");
        }
        // newPwd 和 rePwd是否一样
        if(!rePwd.equals(newPwd)){
            return Result.error("两次填写的新密码不一致");
        }

        //2 调用service完成密码更新
        userService.updatePwd(newPwd);
        // 删除原来的token
//        ValueOperations<String,String> ops = stringRedisTemplate.opsForValue();
//        ops.getOperations().delete(token);
        return Result.success("修改成功");
    }

    @PostMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam String avatar){

        userService.updateAvatar(avatar);
        return Result.success("头像更新成功");
    }

}
